package com.crm.miaohe.controller.authentication;

import com.crm.miaohe.controller.PageResponse;
import com.crm.miaohe.controller.authentication.request.user.AuthUserQueryRequest;
import com.crm.miaohe.controller.authentication.request.user.AuthUserRequest;
import com.crm.miaohe.controller.authentication.response.user.AuthUserDetail;
import com.crm.miaohe.controller.authentication.response.user.AuthUserOverview;
import com.crm.miaohe.controller.customer.request.CustomerParams;
import com.crm.miaohe.service.AuthUserService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/erp/user")
public class AuthUserController {

    private final AuthUserService authUserService;

    public AuthUserController(AuthUserService authUserService) {
        this.authUserService = authUserService;
    }

    @GetMapping
    public ResponseEntity<PageResponse<AuthUserOverview>> overview(@Valid AuthUserQueryRequest request) {
        return ResponseEntity.ok(authUserService.queryUsers(request));
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Void> deleteCustomer(@PathVariable Long id) {
        authUserService.deleteAuthUser(id);
        return ResponseEntity.ok().build();
    }


    @PutMapping("/resetPwd")
    public ResponseEntity<Void> resetCustomerPwd(@RequestBody AuthUserRequest params) {
        authUserService.updatePassword(params);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/updateLocked/{id}")
    public ResponseEntity<Void> updateLocked(@PathVariable Long id) {
        authUserService.updateLocked(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/checkPhoneNumber")
    public ResponseEntity<Boolean> checkPhoneNumber(AuthUserRequest params) {
        return ResponseEntity.ok(authUserService.checkPhoneNumber(params));
    }

    @GetMapping("/details")
    public ResponseEntity<AuthUserDetail> currentAuthUser() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return ResponseEntity.ok(authUserService.currentUser(username));
    }

    @PostMapping("/addUser")
    public ResponseEntity<Void> addAuthUser(@RequestBody @Valid AuthUserRequest params) {
        authUserService.addAuthUser(params);
        return ResponseEntity.ok().build();
    }
}
